package com.estore.view;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        System.out.println("🎉 欢迎来到电子商城！");

        while (true) {
            showMenu();
            int choice = getIntInput("请输入您的选择: ");
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    searchProducts();
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 5:
                    updateCartItem();
                    break;
                case 6:
                    removeFromCart();
                    break;
                case 7:
                    checkout();
                    break;
                case 8:
                    viewProductDetail();
                    break;
                case 9:
                    viewAvailableProducts();
                    break;
                case 0:
                    System.out.println("感谢使用，期待再次光临！");
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }

            // 按回车继续
            if (choice != 0) {
                System.out.print("\n按回车键继续...");
                scanner.nextLine();
            }
        }
    }

    private void showMenu() {
        System.out.println("\n" + "=".repeat(50));
        System.out.println("🏪 电子商城管理系统");
        System.out.println("=".repeat(50));
        System.out.println("1. 📋 浏览所有商品");
        System.out.println("2. 🔍 搜索商品");
        System.out.println("3. 🛒 添加商品到购物车");
        System.out.println("4. 🛍️  查看购物车");
        System.out.println("5. ✏️  修改购物车商品数量");
        System.out.println("6. ❌ 从购物车移除商品");
        System.out.println("7. 💰 结算订单");
        System.out.println("8. 📖 查看商品详情");
        System.out.println("9. 📦 查看有库存商品");
        System.out.println("0. 🚪 退出系统");
        System.out.println("-".repeat(50));
    }

    private void browseProducts() {
        System.out.println("\n--- 所有商品列表 ---");
        List<Product> products = productService.getAllProducts();
        displayProductList(products);
    }

    private void searchProducts() {
        System.out.print("请输入商品名称关键词: ");
        String keyword = scanner.nextLine().trim();

        if (keyword.isEmpty()) {
            System.out.println("搜索关键词不能为空！");
            return;
        }

        List<Product> results = productService.searchProductsByName(keyword);
        if (results.isEmpty()) {
            System.out.println("没有找到包含 '" + keyword + "' 的商品。");
        } else {
            System.out.println("找到 " + results.size() + " 个相关商品:");
            displayProductList(results);
        }
    }

    private void viewAvailableProducts() {
        System.out.println("\n--- 有库存商品列表 ---");
        List<Product> availableProducts = productService.getAvailableProducts();
        displayProductList(availableProducts);
    }

    private void viewProductDetail() {
        System.out.print("请输入商品ID: ");
        String productId = scanner.nextLine().trim();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }

        System.out.println("\n--- 商品详情 ---");
        System.out.println(product);
        System.out.println("库存状态: " + (product.isInStock() ? "✅ 有库存" : "❌ 缺货"));
        if (product.isInStock()) {
            System.out.println("可购买数量: " + product.getStock());
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine().trim();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (!product.isInStock()) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.println("商品: " + product.getName() + " | 当前库存: " + product.getStock());
        int quantity = getIntInput("请输入购买数量: ");

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 检查购物车中已有的数量
        int currentInCart = shoppingCart.getOrDefault(productId, 0);
        if (currentInCart + quantity > product.getStock()) {
            System.out.println("错误：购物车中该商品数量已超过库存！");
            System.out.println("购物车中已有: " + currentInCart + "，不能再添加 " + quantity + " 件");
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, currentInCart + quantity);
        System.out.println("✅ 成功将 '" + product.getName() + "' " + quantity + "件添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("🛒 购物车是空的，快去逛逛吧！");
            return;
        }

        displayCartContents();
    }

    private void updateCartItem() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的！");
            return;
        }

        displayCartContents();

        System.out.print("请输入要修改的商品ID: ");
        String productId = scanner.nextLine().trim();

        if (!shoppingCart.containsKey(productId)) {
            System.out.println("错误：购物车中没有该商品！");
            return;
        }

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("错误：商品不存在！");
            return;
        }

        int newQuantity = getIntInput("请输入新的数量 (输入0将移除商品): ");

        if (newQuantity == 0) {
            shoppingCart.remove(productId);
            System.out.println("已从购物车移除 '" + product.getName() + "'");
        } else if (newQuantity < 0) {
            System.out.println("错误：数量不能为负数！");
        } else if (newQuantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
        } else {
            shoppingCart.put(productId, newQuantity);
            System.out.println("✅ 已更新 '" + product.getName() + "' 数量为 " + newQuantity);
        }
    }

    private void removeFromCart() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的！");
            return;
        }

        displayCartContents();

        System.out.print("请输入要移除的商品ID: ");
        String productId = scanner.nextLine().trim();

        Product product = productService.findProductById(productId);
        if (product != null && shoppingCart.containsKey(productId)) {
            shoppingCart.remove(productId);
            System.out.println("✅ 已从购物车移除 '" + product.getName() + "'");
        } else {
            System.out.println("错误：购物车中没有该商品！");
        }
    }

    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，无法结算！");
            return;
        }

        System.out.println("\n--- 订单结算 ---");
        displayCartContents();

        System.out.print("确认结算吗？(y/N): ");
        String confirm = scanner.nextLine().trim();

        if (!confirm.equalsIgnoreCase("y")) {
            System.out.println("已取消结算。");
            return;
        }

        // 检查库存并处理订单
        boolean success = processOrder();
        if (success) {
            System.out.println("🎉 订单结算成功！感谢您的购买！");
            shoppingCart.clear();
        }
    }

    private boolean processOrder() {
        // 首先检查所有商品库存是否足够
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = productService.findProductById(productId);

            if (product == null) {
                System.out.println("错误：商品 '" + productId + "' 不存在！");
                return false;
            }
            if (!product.hasSufficientStock(quantity)) {
                System.out.println("错误：商品 '" + product.getName() + "' 库存不足！");
                System.out.println("  需要: " + quantity + "，库存: " + product.getStock());
                return false;
            }
        }

        // 扣减库存
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            productService.decreaseStock(productId, quantity);
        }

        return true;
    }

    private void displayProductList(List<Product> products) {
        if (products.isEmpty()) {
            System.out.println("暂无商品。");
            return;
        }

        System.out.printf("%-6s %-20s %-10s %-8s%n", "ID", "商品名称", "价格", "库存");
        System.out.println("-".repeat(50));
        for (Product product : products) {
            String stockStatus = product.isInStock() ?
                    String.valueOf(product.getStock()) : "缺货";
            System.out.printf("%-6s %-20s ¥%-9.2f %-8s%n",
                    product.getId(), product.getName(), product.getPrice(), stockStatus);
        }
    }

    private void displayCartContents() {
        double total = 0.0;
        int totalItems = 0;

        System.out.printf("%-6s %-20s %-10s %-8s %-10s%n",
                "ID", "商品名称", "单价", "数量", "小计");
        System.out.println("-".repeat(60));

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("%-6s %-20s ¥%-9.2f %-8d ¥%-9.2f%n",
                        product.getId(), product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                totalItems += quantity;
            }
        }

        System.out.println("-".repeat(60));
        System.out.printf("商品种类: %d 种 | 商品总数: %d 件%n", shoppingCart.size(), totalItems);
        System.out.printf("订单总计: ¥%.2f%n", total);
    }

    private int getIntInput(String prompt) {
        while (true) {
            System.out.print(prompt);
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                System.out.println("请输入有效的数字！");
                scanner.next(); // 清除无效输入
            }
        }
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}